package com.baidu.ai.aip.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.baidu.ai.aip.utils.Base64Util;
import com.baidu.ai.aip.service.BaiduService;
import com.baidu.ai.aip.utils.FileUtil;
import com.baidu.ai.aip.utils.HttpUtil;
import com.baidu.ai.aip.utils.GsonUtils;
import com.ruoyi.common.core.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import com.baidu.ai.aip.utils.GetToken;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * easydl物体检测
 */
@Controller
public class EasydlObjectDetection extends BaseController {

    @Autowired
    private BaiduService baiduService;
    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    public String easydlObjectDetection(String photo64,Long rate) {



        // 请求接口url
//        String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/detection/puppy";
//        String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/detection/sumei_240308";
        String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/detection/sumei0318";
        try {
            Map<String, Object> map = new HashMap<>();
            final byte[] bytes = FileUtil.readFileByBytes(photo64);
            final String encode = Base64Util.encode(bytes);
            if(encode.equals("")){
                Map<String,String> mapSelf = new HashMap<>();
                mapSelf.put("error_code","336005");
                return JSON.toJSON(mapSelf).toString();
            }
            map.put("image", encode);
            map.put("threshold", rate/100.0);
            String param = GsonUtils.toJson(map);
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
//            GetToken getToken = new GetToken();
            String accessToken = baiduService.getToken();
            String result = HttpUtil.post(url, accessToken, "application/json", param).toString();
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {

//        EasydlObjectDetection.easydlObjectDetection();
    }
}
